//--------------这部分放头文件----------------------
#include <mysql.h>
#include <bits/stdc++.h>
#include "../base/log/Logging.h"

#include "../database/MySQLConnection.h"
#include "../database/ConnectionPool.h"

using namespace std;

MYSQL mysql;
MYSQL_RES *res;//这个结构代表返回行的一个查询结果集
MYSQL_ROW column;//一个行数据的类型安全(type-safe)的表示

void textMysql();//测试方法
bool ConnectMysql();//连接数据库
bool QueryDatabase(string sql);//查询并输出结果
void outMysql();//输出查询结果
bool updateData(string sql);//插入删除修改操作
void FreeConnect();//释放资源
void testMySQLConnection();

void testConnectionPool();

//---------------这部分放源文件------------------------

int main() {
    Logger::setLogLevel(Logger::LogLevel::DEBUG);
    LOG_INFO << "main() start ";

    testConnectionPool();

    return 1;
}

void output(const vector<vector<string> > res) {
    for (auto i : res) {
        for (auto j : i) {
            cout << j << " ";
        }
        cout << endl;
    }
}

void testMySQLConnection() {
    MySQLConnection connection("association", "root", "123456", "localhost", 3330);
    cout << "-------------------------------------------------" << endl;
    output(connection.select("select * from role"));
    cout << "-------------------------------------------------" << endl;
    connection.query("insert into role values (NULL, 'ROLE', '角色')");
    output(connection.select("select * from role"));
    cout << "-------------------------------------------------" << endl;
    connection.query("update role set    name = '角色' where id > 5");
    output(connection.select("select * from role"));
    cout << "-------------------------------------------------" << endl;
    connection.query("delete from role where id > 5");
    output(connection.select("select * from role"));
    cout << "-------------------------------------------------" << endl;
}

void testConnectionPool() {
    ConnectionPool pool(3, "association", "root", "123456", "localhost", 3330);
    ConnectionPool::Connection connection = pool.getConnection();
    output(connection->select("select * from role"));
}

//测试代码
void textMysql() {
    ConnectMysql();
    //  updateData();
    QueryDatabase("select * from client");
    //  updateData();
    // QueryDatabase("select * from association");
    FreeConnect();
}

//连接数据库
bool ConnectMysql() {
    mysql_init(&mysql);//初始化mysql
    mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "UTF8");
    if (!(mysql_real_connect(&mysql,
                             "175.178.51.126",//主机
                             "root",//用户名
                             "123456",//密码
                             "association",//数据库名 必须是已经存在的 我的mysql大小写不敏感
                             3330,//端口号 默认的0或者3306
                             NULL, 0//最后两个参数的常用写法 几乎都是这两个
    ))) {
        cout << "Error connecting to database:" + (string) mysql_error(&mysql) << endl;
        return false;
    } else {
        cout << "Connected..." << endl;
        cout << "set utf8 : " << mysql_query(&mysql, "set names utf8") << endl;
        //设置编码格式 否则mysql里中文乱码
// 如果查询成功，返回0。如果出现错误，返回非0值
        return true;
    }
}

//所有的数据库操作都是先写个sql语句
//然后用mysql_query(&mysql,query)来完成
//包括创建数据库或表 增删改查
bool updateData(string sql) {
    // 执行SQL语句
    // 0 执行成功
    // 1 执行失败
    if (mysql_query(&mysql, sql.c_str())) {//mysql_query第二个参数只接受const cahr* 需要将string类型转化
        cout << "Update failed ( " + (string) mysql_error(&mysql) + " )" << endl;
        return false;
    } else {
        cout << "Update success..." << endl;
        return true;
    }
}

//查询并输出
bool QueryDatabase(string sql) {
    // 执行SQL语句
    // 0 执行成功
    // 1 执行失败
    if (mysql_query(&mysql, sql.c_str())) {//mysql_query第二个参数只接受const cahr* 需要将string类型转化
        cout << "Query failed ( " + (string) mysql_error(&mysql) + " )" << endl;
        return false;
    } else {
        cout << "query success" << endl;
    }

    //获得结果集 MYSQL_RES *res;
    if (!(res = mysql_store_result(&mysql))) {
        cout << "Couldn't get result from " + (string) mysql_error(&mysql) << endl;
        return false;
    }
    outMysql();//打印结果
    return true;
}

//输出结果
void outMysql() {
    //打印数据行数
    cout << "number of dataline returned: " << mysql_affected_rows(&mysql) << endl;

    char *field[32];//字段名

    int num = mysql_num_fields(res);//获取列数
    for (int i = 0; i < num; ++i) {//获取字段名
        field[i] = mysql_fetch_field(res)->name;
    }

    for (int i = 0; i < num; ++i) {
        cout << (string) field[i] << "    ";
    }
    cout << endl;

    while (column = mysql_fetch_row(res)) {//获取一行数据
        for (int i = 0; i < num; ++i) {
            cout << column[i] << "    ";
        }
        cout << endl;
    }
}

//释放资源
void FreeConnect() {
    mysql_free_result(res);
    // 这里是释放结果集
    mysql_close(&mysql);
}